
from flask import Flask, render_template, url_for, request, redirect, jsonify
from flask_bootstrap import Bootstrap

import os
import model

import requests
import urllib.request
import json

import numpy as np

import grpc_request # 调用grpc客户端

import re # 正则表达式, 过滤url

import process_arr_message # 引入处理gprc返回结果的函数

app = Flask(__name__, template_folder='Template')
Bootstrap(app)

"""
Routes
"""

class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)

@app.route('/')
def hello():
    return "你好"

@app.route('/predict', methods=['GET','POST'])
def index():
    if request.method == 'POST': 
        uploaded_file = request.files['file'] # 接收文件
        if uploaded_file.filename != '': # 接受的文件名不为空
            image_path = os.path.join('static', uploaded_file.filename) # 图片保存地址
            uploaded_file.save(image_path) # 保存图片

            # 得到预测结果的数组
            result_arr_web = grpc_request.pre_grpc(image_path) 
            
            # 得到处理好的结果
            result = process_arr_message.process_arr(result_arr_web)
            result['image_path'] = image_path
            # 渲染模板, 返回结果
            return render_template('result.html', result = result)
    return render_template('index.html')

# 传入url, 下载图片并进行预测
@app.route('/predict_url', methods=['GET', 'POST'])
def request_url():
    if request.method == 'POST': 
        # 获取从微信传过来的参数, 转换成json形式
        url_in_json_fmt = request.values.get('img_url_str') # 得到json格式的url
        print (json.loads(url_in_json_fmt))
        img_url = json.loads(url_in_json_fmt)
        
        # 下载图片, 获取图像路径
        download_img(img_url) 
        # class_name = grpc_request.request_server(x, server_url)
        img_path = '/usr/share/nginx/skinmodel/APP/static02/img.jpg'

        # 根据模型关键词选择要用的模型, 暂时不用, 完善模型搭载后再启用

            # accepted_selected_model = request.values.get("selected_model") #接受小程序传来的选中的模型
            # print (json.loads(accepted_selected_model)) 
            # model_key = json.loads(accepted_selected_model)

            # if model_key in model_port_index : 
            #     model_port = model_port_index[model_key]
            # else: 
            #     return "Can't find this model"

        # 得到预测结果的数组
        # 得到处理好的结果
        result_arr = grpc_request.pre_grpc(img_path) 
        result = process_arr_message.process_arr(result_arr)
        # result_json = jsonify(result)
        result = json.dumps(result, cls=NpEncoder)
        return result


# 实现下载图片函数
def download_img(img_url):
    print (img_url)

    # requests库
    # headers模拟浏览器访问
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                        'Chrome/51.0.2704.63 Safari/537.36'}
    r = requests.get(img_url, headers=headers, stream=True)
    print(r.status_code) # 返回状态码
    if r.status_code == 200:
        open('static02/img.jpg', 'wb').write(r.content) # 将内容写入图片
        print("done")
    del r


if __name__ == '__main__':
    app.run(debug = True)